package com.klm.common.util;

import com.klm.cache.TranslateCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * 签名工具类 - 服务端使用
 */
@Component
public class SignUtil {
    
    @Autowired
    private TranslateCacheManager cacheManager;
    
    // 签名有效期（毫秒）
    private static final long SIGNATURE_EXPIRATION = TimeUnit.MINUTES.toMillis(5);
    
    // 缓存key前缀
    private static final String CACHE_KEY_PREFIX = "signature:timestamp:";

    /**
     * 验证签名
     * @param appSecret 应用密钥
     * @param timestamp 时间戳
     * @param signature 签名
     * @return 是否验证通过
     */
    public boolean verifySignature(String appSecret, long timestamp, String signature) {
        // 1. 验证时间戳是否在有效期内
        long currentTime = System.currentTimeMillis();
        if (Math.abs(currentTime - timestamp) > SIGNATURE_EXPIRATION) {
            return false;
        }

        // 2. 验证时间戳是否已使用过
        String cacheKey = CACHE_KEY_PREFIX + appSecret + ":" + timestamp;
        if (cacheManager.getCache(cacheKey, Long.class) != null) {
            return false;
        }

        // 3. 验证签名
        try {
            String expectedSignature = generateSignature(appSecret, timestamp);
            if (expectedSignature.equals(signature)) {
                // 4. 签名验证通过，将时间戳加入缓存
                cacheManager.getCache(cacheKey, Long.class);
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 生成签名（用于验证）
     */
    private String generateSignature(String appSecret, long timestamp) {
        try {
            String data = timestamp + "";
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            mac.init(secretKeySpec);
            byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(hash);
        } catch (Exception e) {
            throw new RuntimeException("Failed to generate signature", e);
        }
    }
}
